package org.example.partnerbacked.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
<<<<<<< HEAD
import jakarta.annotation.Resource;
import org.example.partnerbacked.common.ErrorCode;
import org.example.partnerbacked.exception.BusinessException;

import org.example.partnerbacked.model.Team;
import org.example.partnerbacked.model.User;
import org.example.partnerbacked.model.UserTeam;
import org.example.partnerbacked.service.TeamService;
import org.example.partnerbacked.mapper.TeamMapper;
import org.example.partnerbacked.service.UserService;
import org.example.partnerbacked.service.UserTeamService;
import org.springframework.beans.factory.annotation.Autowired;
=======
import org.example.partnerbacked.model.Team;
import org.example.partnerbacked.service.TeamService;
import org.example.partnerbacked.mapper.TeamMapper;
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;



/**
* @author 70556
* @description 针对表【team(队伍)】的数据库操作Service实现
* @createDate 2024-12-02 22:09:49
*/
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
    implements TeamService{
    @Resource
    private UserService userService;
    @Resource
    private UserTeamService userTeamService;
    @Autowired
    private TeamMapper teamMapper;

    /**
     * 创建队伍 其中status不传默认是0
     * @param team
     * @param user
     * @return
     */
    @Transactional
    @Override
    public long addTeam(Team team, User user) {
        if(team==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(team.getName().length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍名称过长");
        }
        if(team.getDescription()!=null&&team.getDescription().length()>1024){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍描述过长");
        }
        if(team.getMaxNum()<=0||team.getMaxNum()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍人数不在范围");
        }

        //队伍设置的过期时间不对
        if(team.getExpireTime()!=null&&team.getExpireTime().isBefore(LocalDateTime.now())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍过期设置时间不合法");
        }
        if(team.getStatus()==2&&(team.getPassword()==null||team.getPassword().length()>32)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不合法");
        }
        QueryWrapper<Team> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userId",user.getId());
         long count = this.count(queryWrapper);
         if(count>=5){
             throw new BusinessException(ErrorCode.PARAMS_ERROR,"最多创建5个队伍");
         }
         team.setUserId(user.getId());
        boolean save = this.save(team);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"创建队伍失败");
        }
        UserTeam userTeam=new UserTeam();
        userTeam.setUserId(user.getId());
        userTeam.setTeamId(team.getId());
        userTeam.setJoinTime(LocalDateTime.now());
       Boolean result = userTeamService.save(userTeam);
       if(!result){
           throw new BusinessException(ErrorCode.SYSTEM_ERROR,"创建队伍失败");
       }
        return 0;
    }

    /**
     * 解释队伍
     * @param teamId
     * @param user
     * @return
     */
     @Transactional
    @Override
    public boolean deleteTeam(Long teamId, User user) {
       if(user==null) throw new BusinessException(ErrorCode.NOT_LOGIN);
       if(teamId==null||teamId<=0){
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"不存在这样的队伍");
       }
       QueryWrapper<Team> queryWrapper=new QueryWrapper<>();
       queryWrapper.eq("id",teamId);
       Team team = this.getOne(queryWrapper);
       if(team==null){
           throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
       }
       if(!team.getUserId().equals(user.getId())){
           throw new BusinessException(ErrorCode.NO_AUTH,"没有权限");
       }
       Boolean result = this.removeById(teamId);
        QueryWrapper<UserTeam> userTeamQueryWrapper=new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId",teamId);
        try {
            deleteUserTeamByTeamId(teamId);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"解散失败");
        }
       if(!result) throw new BusinessException(ErrorCode.SYSTEM_ERROR,"解散失败");
        return true;
    }

    /**
     * 删除所有加人teamId的的数据
     * @param teamId
     */
    private void deleteUserTeamByTeamId(Long teamId) {
        //删除所有加人teamId的的数据
        QueryWrapper<UserTeam> userTeamQueryWrapper=new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId",teamId);
        Boolean result = userTeamService.remove(userTeamQueryWrapper);

    }

    /**
     * join team
     * @param verified
     * @param teamId
     * @param user
     * @return
     */
    @Override
    public boolean joinTeam(String verified,Long teamId, User user) {
        if(user==null) throw new BusinessException(ErrorCode.NOT_LOGIN);
        if(teamId==null||teamId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不存在这样的队伍");
        }
        QueryWrapper<Team> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",teamId);
        Team team = this.getOne(queryWrapper);
        //判断队伍是否过期
        if(team.getExpireTime()!=null&&team.getExpireTime().isAfter(LocalDateTime.now())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍已过期");
        }
        if(team==null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
        }
        QueryWrapper<UserTeam> userTeamQueryWrapper=new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId",teamId);
        long count = userTeamService.count(userTeamQueryWrapper);
        if(count>=team.getMaxNum()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍已满");
        }
        if(team.getIsDelete()==1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍已解散");
        }
        //是否加密
        if(team.getStatus()==2&&!team.getPassword().equals(verified)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不正确");
        }
         QueryWrapper<UserTeam> queryWrapper1=new QueryWrapper<>();
        UserTeam userTeam=new UserTeam();
        userTeam.setUserId(user.getId());
        userTeam.setTeamId(teamId);
        userTeam.setJoinTime(LocalDateTime.now());
        Boolean RESULT = userTeamService.save(userTeam);
        if(!RESULT) throw new BusinessException(ErrorCode.SYSTEM_ERROR,"加入失败");
        return true;
    }

    /**
     * 退出队伍 待完善
     * @param teamId
     * @param user
     * @return
     */
    @Transactional
    @Override
    public boolean quitTeam(Long teamId, User user) {
        if(user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(teamId==null||teamId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不存在这样的队伍");
        }
        QueryWrapper<Team> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",teamId);
        Team team = this.getOne(queryWrapper);
        if(team==null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
        }
        //要不要判断队伍已解散的状态？

        //判断是否是队长
        if(!team.getUserId().equals(user.getId())){
            QueryWrapper<UserTeam> userTeamQueryWrapper=new QueryWrapper<>();
            userTeamQueryWrapper.eq("userId",user.getId());
            userTeamQueryWrapper.eq("teamId",teamId);
           Boolean result = userTeamService.remove(userTeamQueryWrapper);
           if(!result){
               throw new BusinessException(ErrorCode.SYSTEM_ERROR,"退出失败");
           }
           return true;
        }
        //是队长退出队伍，是直接解散还是把队长转给别人
        //这里我们是实现队长退出，就相等于退出队无
        try {
            deleteUserTeamByTeamId(teamId);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"退出失败");
        }

        return true;
    }

    /**
     * 更新队伍
     * @param team
     * @return
     */
    @Override
    public boolean updated(Team team, User user) {
          if(user==null){
              throw new BusinessException(ErrorCode.NOT_LOGIN);
          }
          if(team.getId()==null||team.getId()<=0){
              throw new BusinessException(ErrorCode.PARAMS_ERROR,"不存在这样的队伍");
          }
          QueryWrapper<Team> queryWrapper=new QueryWrapper<>();
          queryWrapper.eq("id",team.getId());
          Team oldTeam = this.getOne(queryWrapper);
          if(oldTeam==null){
              throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
          }
          if(!oldTeam.getUserId().equals(user.getId())){
              throw new BusinessException(ErrorCode.PARAMS_ERROR,"没有权限");
          }
          queryWrapper=new QueryWrapper<>();
          if(team.getPassword()!=null){
              queryWrapper.eq("password",team.getPassword());
          }
          if(team.getExpireTime()!=null){
              queryWrapper.eq("expireTime",team.getExpireTime());
          }
          if(team.getMaxNum()!=null){
              queryWrapper.eq("maxNum",team.getMaxNum());
          }
          if(team.getName()!=null){
              queryWrapper.eq("name",team.getName());
          }
          if(team.getDescription()!=null){
              queryWrapper.eq("description",team.getDescription());
          }
          Integer result =  teamMapper.update(team,queryWrapper);
          if(result==0) throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
          return true;
    }
}




